package com.atguigu.springcloud.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Date;

/**
 * 全局日志
 */
@Component
public class MyLogGateWayFilter implements GlobalFilter, Ordered {
    Logger logger = LoggerFactory.getLogger(MyLogGateWayFilter.class);

    /**
     * 过滤器的逻辑
     * 请求进来首先会访问到gateway的过滤器
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        logger.info("welcome to GateWay  MyLogGateWayFilter" + new Date());
        //请求必须要带 uname
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (null == uname) {
            logger.info("用户名字为null  非法的用户名");
            //设置响应为不被允许
            exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
